package com.lanou.zy.projecta.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lanou.zy.projecta.R;
import com.lanou.zy.projecta.database.DBHelper;
import com.lanou.zy.projecta.search.ClearEditText;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.UMQQSsoHandler;

import java.util.Map;
import java.util.Set;


/**
 * Created by dllo on 15/10/24.
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private Toast toast;
    private Button loginBtn;
    private ClearEditText loginName, loginPsw;
    private TextView intoRegister_Tv;
    private ImageView backToUserIv, loginWeibo_Iv, loginQQ_Iv;
    private DBHelper helper;
    private SharedPreferences sp;
    private UMSocialService mController;
//    private Context mcontext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        initData();
    }

    private void initData() {

    }

    private void initView() {
        loginName = (ClearEditText) findViewById(R.id.loginName);
        loginPsw = (ClearEditText) findViewById(R.id.loginPsw);
        loginPsw.setTransformationMethod(PasswordTransformationMethod.getInstance());
        intoRegister_Tv = (TextView) findViewById(R.id.intoRegister_Tv);
        intoRegister_Tv.setOnClickListener(this);
        backToUserIv = (ImageView) findViewById(R.id.backToUserIv);
        backToUserIv.setOnClickListener(this);
        loginBtn = (Button) findViewById(R.id.loginBtn);
        loginBtn.setOnClickListener(this);
        loginWeibo_Iv = (ImageView) findViewById(R.id.loginWeibo_Iv);
        loginWeibo_Iv.setOnClickListener(this);
        loginQQ_Iv = (ImageView) findViewById(R.id.loginQQ_Iv);
        loginQQ_Iv.setOnClickListener(this);
        helper = DBHelper.getInstance();
        sp = getSharedPreferences("zy", Context.MODE_PRIVATE);

        mController = UMServiceFactory.getUMSocialService("com.umeng.login");
        UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        qqSsoHandler.addToSocialSDK();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loginBtn:
                if (checkEditText()) {
                    Intent intent = new Intent(this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }

                break;
            case R.id.intoRegister_Tv:
                Intent intentToRegister = new Intent(this, RegisterActivity.class);
                startActivity(intentToRegister);
                finish();
                break;

            case R.id.backToUserIv:
                onBackPressed();
                finish();
                break;

            case R.id.loginWeibo_Iv:
                isdoOauthVerify();
                break;

            case R.id.loginQQ_Iv:
//                onClickLogin();
                QQLogin();
                break;
        }
    }

    /**
     * 用户名和密码的验证
     */
    private String name;
    private String psw;

    private boolean checkEditText() {
        name = loginName.getText().toString().trim();
        psw = loginPsw.getText().toString().trim();
        if (name != null && name.length() > 0) {
            if (psw != null && psw.length() > 0) {
                if (helper.isUserSaves(name)) {
                    if (helper.getUserByUserName(name).getUserPsw().equals(psw)) {
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean("login", true);
                        editor.commit();
                        return true;
                    } else {
                        Toast.makeText(this, "密码不正确，请重新输入", Toast.LENGTH_SHORT).show();
                        return false;
                    }
                } else {
                    Toast.makeText(this, "用户名不正确，请重新输入", Toast.LENGTH_SHORT).show();
                    return false;
                }
            } else {
                Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
                return false;
            }
        } else {
            Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    /**
     * 新浪微博登录
     **/
    private void isdoOauthVerify() {
        mController.doOauthVerify(this, SHARE_MEDIA.SINA, new SocializeListeners.UMAuthListener() {
            @Override
            public void onError(SocializeException e, SHARE_MEDIA platform) {
            }

            @Override
            public void onComplete(Bundle value, SHARE_MEDIA platform) {
                if (value != null && !TextUtils.isEmpty(value.getString("uid"))) {
                    Toast.makeText(LoginActivity.this, "授权成功.", Toast.LENGTH_SHORT).show();
                    Intent intent2 = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent2);
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancel(SHARE_MEDIA platform) {
            }

            @Override
            public void onStart(SHARE_MEDIA platform) {
            }
        });
    }

    /**
     * QQ登录
     **/
    private void QQLogin() {

        mController.doOauthVerify(this, SHARE_MEDIA.QQ, new SocializeListeners.UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA platform) {
                Toast.makeText(LoginActivity.this, "授权开始", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(SocializeException e, SHARE_MEDIA platform) {
                Toast.makeText(LoginActivity.this, "授权错误", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete(Bundle value, SHARE_MEDIA platform) {
                Toast.makeText(LoginActivity.this, "授权完成", Toast.LENGTH_SHORT).show();
                //获取相关授权信息
                mController.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, new SocializeListeners.UMDataListener() {
                    @Override
                    public void onStart() {
                        Toast.makeText(LoginActivity.this, "获取平台数据开始...", Toast.LENGTH_SHORT).show();
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putBoolean("login", true);
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onComplete(int status, Map<String, Object> info) {
                        if (status == 200 && info != null) {
                            StringBuilder sb = new StringBuilder();
                            Set<String> keys = info.keySet();
                            for (String key : keys) {
                                sb.append(key + "=" + info.get(key).toString() + "\r\n");
                            }
                            Log.d("TestData", sb.toString());
                        } else {
                            Log.d("TestData", "发生错误：" + status);
                        }
                    }
                });
            }

            @Override
            public void onCancel(SHARE_MEDIA platform) {
                Toast.makeText(LoginActivity.this, "授权取消", Toast.LENGTH_SHORT).show();
            }
        });
    }


}
